package com.example.personalaccount.service.impl;

import com.example.personalaccount.dto.UserInformDto;
import com.example.personalaccount.entity.UserInform;
import com.example.personalaccount.handler.SecurityGetUserUtil;
import com.example.personalaccount.repository.UserInformRepository;
import com.example.personalaccount.service.UserInformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userInformService")
public class UserInformServiceImpl implements UserInformService {
    @Autowired
    private UserInformRepository userInformRepository ;

    @Override
    public UserInform getUserInform(String id) {
        UserInform userInform = userInformRepository.findById(id).orElse(null);
        if (userInform == null)
            return null;
        return userInform;
    }

    @Override
    public List<UserInform> getUserInformList(String username) {
        return userInformRepository.getUserInformByUsernameLike(username);
    }

    @Override
    public UserInform getByUserId(long userId) {
        return userInformRepository.getUserInformByUserId(userId);
    }

    @Override
    public UserInform updateUserInform(UserInformDto userInformDto) {
        SecurityGetUserUtil s = new SecurityGetUserUtil();
        if (s.getUser().getId() != userInformDto.getUserId() && !s.getUser().getRole().equals("ADMIN") )
        {
            throw new RuntimeException("please change yourself userInform");
        }
        UserInform userInformByUserId = userInformRepository.getUserInformByUserId(userInformDto.getUserId());
        userInformByUserId.setDescription(userInformDto.getDescription());
        userInformByUserId.setUsername(userInformDto.getUsername());
        userInformByUserId.setImgId(userInformDto.getImgId());
        userInformByUserId.setStatus(userInformDto.isStatus());
        return userInformRepository.save(userInformByUserId);
    }

    @Override
    public UserInform changeUserImg(String imgId, long userId) {
        UserInform user = userInformRepository.getUserInformByUserId(userId);
        user.setImgId(imgId);
        return userInformRepository.save(user);
    }

    @Override
    public UserInform changeUsername(String username, long userId) {
        UserInform user = userInformRepository.getUserInformByUserId(userId);
        user.setImgId(username);
        return userInformRepository.save(user);
    }
}
